﻿using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;

namespace StockLib.UserData
{
    public class TabFileLoader
    {
        public virtual void Load()
        {
            FileInfo fi = new FileInfo(StockUserData.Instance.GetFileName(UserDataType.Tab));
            if (!fi.Exists)
                return;

            FileStream fs = null;
            StreamReader sr = null;

            try
            {
                fs = new FileStream(fi.FullName, FileMode.Open, FileAccess.Read, FileShare.Read);
                sr = new StreamReader(fs, Encoding.Default);

                StockTab tab = null;
                while (!sr.EndOfStream)
                {
                    string line = sr.ReadLine();
                    if (!string.IsNullOrEmpty(line))
                    {
                        line = line.Trim();
                    }
                    if (string.IsNullOrEmpty(line))
                        continue;

                    /*string[] parts = line.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    if (parts.Length != 2)
                        continue;

                    tab = new StockTab();
                    tab.Name = parts[0];
                    tab.BlockId = parts[1];*/

                    tab = new StockTab();
                    tab.BlockId = line;
                    if (tab.BlockId.EndsWith("."))
                    {
                        tab.Name = Regex.Replace(tab.BlockId, @"^(.+)\.$", @"$1");
                    }
                    else
                    {
                        tab.Name = Regex.Replace(tab.BlockId, @"^(.+)\.(.+)$", @"$2");
                    }                    

                    StockTabContainer.Instance.Add(tab);
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex.ToString());
                throw ex;
            }
            finally
            {
                if (sr != null)
                {
                    sr.Close();
                    sr.Dispose();
                }

                if (fs != null)
                {
                    fs.Close();
                    fs.Dispose();
                }
            }
        }
    }
}
